package easymall.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import easymall.clients.CategoryService;
import easymall.clients.ProductsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import easymall.po.Category;
import easymall.po.Products;

@Controller("productsController")
public class ProductsController {
	@Autowired
	private ProductsService productsService;

	@Autowired
	private CategoryService categoryService;
	
	@RequestMapping("/prodlist")
	public String prodlist(String name, String category, Double minprice, Double maxprice, Model model) {
		//查找商品表中所有的商品类别
		List<Category> categorys = categoryService.allcategorys();
		model.addAttribute("categorys", categorys);
		
		//为搜索条件设置默认值，并检查条件是否合法
		double _minPrice = 0;
		Double _maxPrice = Double.MAX_VALUE;
		
//		String reg = "^\\d+$";
//		if(minprice != null && !"".equals(minprice.trim()) && minprice.matches(reg)) {
//			_minPrice = Double.parseDouble(minprice);
//			model.addAttribute("minprice", _minPrice);
//		}
//		if(maxprice != null && !"".equals(maxprice.trim()) && maxprice.matches(reg)) {
//			_maxPrice = Double.parseDouble(maxprice);
//			model.addAttribute("maxprice", _maxPrice);
//		}
		
		if(minprice!=null) {
			_minPrice = minprice;
			model.addAttribute("minprice", _minPrice);
		}
		if(maxprice != null ) {
			_maxPrice = maxprice;
			model.addAttribute("maxprice", _maxPrice);
		}
		
		
		//创建map用于存放查询条件
		Map<String, Object> map = new HashMap<>();
		map.put("name", name);
		map.put("category", category);
		map.put("minPrice", _minPrice);
		map.put("maxPrice", _maxPrice);
		
		List<Products> products = productsService.prodlist(map);
		model.addAttribute("name", name);
		model.addAttribute("category", category);
		model.addAttribute("products", products);
		
		return "prod_list";
	}
	
	@RequestMapping("/prodInfo")
	public String prodInfo(String pid, Model model) {
		Products product = productsService.oneProduct(pid);
		model.addAttribute("product", product);
		//返回到/WEB-INF/jsp/prod_info.jsp
		return "prod_info";
	}
	
	@RequestMapping(value = "/prodclass/{proclass}", method = RequestMethod.GET)
	public String prodclass(@PathVariable Integer proclass, Model model) {
		List<Products> products = productsService.proclass(proclass);
		model.addAttribute("products", products);
		//返回到/WEB-INF/jsp/prod_info.jsp
		return "forward:/WEB-INF/jsp/prod_list.jsp";
	}
}
